package logger

import (
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
	"path/filepath"
	"strings"
)

var Logger *zap.Logger

// InitLogger 初始化日志系统
func InitLogger() error {
	// 获取日志配置
	logLevel := viper.GetString("logger.level")
	logPath := viper.GetString("logger.path")
	logFilename := viper.GetString("logger.filename")
	//maxSize := viper.GetInt("logger.max_size")
	//maxAge := viper.GetInt("logger.max_age")
	//maxBackups := viper.GetInt("logger.max_backups")
	//compress := viper.GetBool("logger.compress")
	consoleOutput := viper.GetBool("logger.console_output")

	// 确保日志目录存在
	if err := os.MkdirAll(logPath, 0755); err != nil {
		return err
	}

	// 创建日志文件的完整路径
	logFile := filepath.Join(logPath, logFilename)

	// 设置日志级别
	var level zapcore.Level
	switch strings.ToLower(logLevel) {
	case "debug":
		level = zap.DebugLevel
	case "info":
		level = zap.InfoLevel
	case "warn", "warning":
		level = zap.WarnLevel
	case "error":
		level = zap.ErrorLevel
	case "dpanic":
		level = zap.DPanicLevel
	case "panic":
		level = zap.PanicLevel
	case "fatal":
		level = zap.FatalLevel
	default:
		level = zap.InfoLevel
	}

	// 创建编码器配置
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		MessageKey:     "message",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.StringDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}

	// 创建输出
	outputs := []zapcore.WriteSyncer{}

	// 添加文件输出
	fileSyncer, _, err := zap.Open(logFile)
	if err != nil {
		return err
	}
	outputs = append(outputs, fileSyncer)

	// 如果配置了控制台输出，添加控制台输出
	if consoleOutput {
		outputs = append(outputs, zapcore.AddSync(os.Stdout))
	}

	// 创建核心
	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderConfig),
		zapcore.NewMultiWriteSyncer(outputs...),
		level,
	)

	// 创建logger
	Logger = zap.New(core, zap.AddCaller(), zap.AddStacktrace(zap.ErrorLevel))

	return nil
}

// Debug 记录Debug级别日志
func Debug(msg string, fields ...zap.Field) {
	if Logger != nil {
		Logger.Debug(msg, fields...)
	}
}

// Info 记录Info级别日志
func Info(msg string, fields ...zap.Field) {
	if Logger != nil {
		Logger.Info(msg, fields...)
	}
}

// Warn 记录Warn级别日志
func Warn(msg string, fields ...zap.Field) {
	if Logger != nil {
		Logger.Warn(msg, fields...)
	}
}

// Error 记录Error级别日志
func Error(msg string, fields ...zap.Field) {
	if Logger != nil {
		Logger.Error(msg, fields...)
	}
}

// DPanic 记录DPanic级别日志
func DPanic(msg string, fields ...zap.Field) {
	if Logger != nil {
		Logger.DPanic(msg, fields...)
	}
}

// Panic 记录Panic级别日志
func Panic(msg string, fields ...zap.Field) {
	if Logger != nil {
		Logger.Panic(msg, fields...)
	}
}

// Fatal 记录Fatal级别日志
func Fatal(msg string, fields ...zap.Field) {
	if Logger != nil {
		Logger.Fatal(msg, fields...)
	}
}

// CloseLogger 关闭日志系统
func CloseLogger() error {
	if Logger != nil {
		return Logger.Sync()
	}
	return nil
}
